package com.example.wangyongdong.bearsqlitedemo;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.wangyongdong.bearsqlitedemo.add.AddActivity;
import com.example.wangyongdong.bearsqlitedemo.db.DatabaseTool;
import com.example.wangyongdong.bearsqlitedemo.db.RxSQLite;
import com.example.wangyongdong.bearsqlitedemo.entity.CarEntity;
import com.example.wangyongdong.bearsqlitedemo.oilcost.OilCostFragment;
import com.example.wangyongdong.bearsqlitedemo.oilcostmoney.OilCostMoneyFragment;
import com.example.wangyongdong.bearsqlitedemo.oilrank.OilRankFragment;
import com.example.wangyongdong.bearsqlitedemo.oilwear.OilWearFragment;
import com.example.wangyongdong.bearsqlitedemo.spadd.SpAddActivity;
import com.example.wangyongdong.bearsqlitedemo.spinner.CarSpinnerAdapter;
import com.example.wangyongdong.bearsqlitedemo.view.SlidingMenu;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class MainActivity extends AppCompatActivity {

    private Spinner mSpinner;
    private CarSpinnerAdapter carSpinnerAdapter;
    private MainAdapter adapter;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private ImageView addIv;
    private List<Fragment> fragments;
    private List<CarEntity> cars;
    private int newPosition;
    private AlertDialog dialog;
    private SlidingMenu slidingMenu;
    private CarEntity myCar;

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSpinner = (Spinner) findViewById(R.id.spinner);
        slidingMenu = (SlidingMenu) findViewById(R.id.sliding_menu);


        fragments = new ArrayList<>();
        fragments.add(new OilWearFragment());
        fragments.add(new OilRankFragment());
        fragments.add(new OilCostFragment());
        fragments.add(new OilCostMoneyFragment());

        adapter = new MainAdapter(getSupportFragmentManager(), fragments);

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);


        addIv = (ImageView) findViewById(R.id.add_content);
        addIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MainActivity", "888:" + 888);
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
            }
        });

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = adapter.getTabView(i, this);
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            assert tab != null;
            tab.setCustomView(tabView);
        }
        cars = new ArrayList<>();
        myCar = new CarEntity();
        querySp();
//        queryDialog();

        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                //找出了车辆管理
                if (position == mSpinner.getCount() - 1) {
                    customDialog();
                }else {
                //切换车辆
//                DatabaseTool.getInstance().changeSelectedCar((int) id);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }


    private void customDialog() {

//        DialogInterface.OnClickListener dialogOnClickListener = new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                switch (which){
//                    case Dialog.BUTTON_POSITIVE:
//                        int newId = cars.get(newPosition).get_id();
//                        DatabaseTool.getInstance().removeCar(newId);
//                        Toast.makeText(MainActivity.this, "删除:" + String.valueOf(newPosition), Toast.LENGTH_SHORT).show();
//                        queryDialog();
//                        break;
//                    case Dialog.BUTTON_NEGATIVE:
//                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
//                        break;
//                }
//            }
//        };
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("删除车辆");
//        builder.setMessage("删除将不可恢复,您确定删除" + myCar.getName() + ",以及它的所有油耗数据吗？");
//        builder.setIcon(R.mipmap.ic_launcher);
//        builder.setPositiveButton("确认",dialogOnClickListener);
//        builder.setNegativeButton("取消",dialogOnClickListener);
//        builder.create().show();

        View view = LayoutInflater.from(this).inflate(R.layout.view_dialog, null);
        ImageView addDialogIv = (ImageView) view.findViewById(R.id.add_dialog_iv);
        addDialogIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SpAddActivity.class);
                startActivity(intent);
            }
        });
        TextView closeTv = (TextView) view.findViewById(R.id.close_tv);

        ListView listView = (ListView) view.findViewById(R.id.dialog_listview);
        ListAdapter listAdapter = new ListAdapter(MainActivity.this);
        listAdapter.setCars(cars);
        listView.setAdapter(listAdapter);
        final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
        dialog.setView(view);
        dialog.show();

        closeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }

    private void queryDialog() {
        RxSQLite.queryAllCars()
                .map(new Function<List<CarEntity>, List<CarEntity>>() {
                    @Override
                    public List<CarEntity> apply(@NonNull List<CarEntity> carEntities) throws Exception {
                        return DatabaseTool.getInstance().queryCars();
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<CarEntity>>() {
                    @Override
                    public void accept(@NonNull List<CarEntity> carEntities) throws Exception {
//                        ListAdapter listAdapter = new ListAdapter(MainActivity.this);
//                        listAdapter.setCars(carEntities);
//                        listView.setAdapter(listAdapter);
                    }
                });
    }

    private void querySp() {
        RxSQLite.queryAllCars()
                .map(new Function<List<CarEntity>, List<CarEntity>>() {
                    @Override
                    public List<CarEntity> apply(@NonNull List<CarEntity> carEntities) throws Exception {
                        CarEntity car = new CarEntity();
                        car.setName("车辆管理");
                        car.set_id(-1);
                        carEntities.add(car);
                        if (carEntities.size() == 1) {
                            myCar.setName("我的小车");
                            myCar.setSelected(1);
                            carEntities.add(0, myCar);
                            DatabaseTool.getInstance().addCar(myCar);
                        }
                        cars = carEntities;
                        return carEntities;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<CarEntity>>() {
                    @Override
                    public void accept(@NonNull List<CarEntity> carEntities) throws Exception {
                        carSpinnerAdapter = new CarSpinnerAdapter(MainActivity.this, cars);
                        mSpinner.setAdapter(carSpinnerAdapter);
                    }
                });
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
